//
//  HMComposePictrueView.swift
//  Black22
//
//  Created by Apple on 16/11/25.
//  Copyright © 2016年 KY. All rights reserved.
//

import UIKit
//  重用标记
private let HMComposePictrueViewCellIdentifer = "HMComposePictrueViewCellIdentifer"

//  撰写配图
class HMComposePictrueView: UICollectionView {
    //  添加图片执行的闭包回调
    var addImageCallBack: (()->())?
    //  图片数据源
     lazy var images: [UIImage] = [UIImage]()
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        let flowLayout = UICollectionViewFlowLayout()
        
        
        
        super.init(frame: frame, collectionViewLayout: flowLayout)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        //  默认隐藏
        isHidden = true
        
        register(HMComposePictrueViewCell.self, forCellWithReuseIdentifier: HMComposePictrueViewCellIdentifer)
        //  设置数据源代理
        dataSource = self
        //  设置代理
        delegate = self
    }
    
    func addImage(image: UIImage) {
        isHidden = false
        //  大于等于9张图片，隐藏配图
        if images.count >= 9 {
            return
        }
        images.append(image)
        reloadData()
    }
    

    override func layoutSubviews() {
        super.layoutSubviews()
        let itemMargin: CGFloat = 5
        //每项的宽度
        let itemWidth = (width - 2 * itemMargin) / 3
        let flowLayout = collectionViewLayout as! UICollectionViewFlowLayout
        flowLayout.itemSize = CGSize(width: itemWidth, height: itemWidth)
        flowLayout.minimumLineSpacing = itemMargin
        flowLayout.minimumInteritemSpacing = itemMargin
    }
    
}

extension HMComposePictrueView: UICollectionViewDataSource, UICollectionViewDelegate {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if images.count == 0 || images.count == 9 {
            return images.count
        } else {
            return images.count + 1
        }
        
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: HMComposePictrueViewCellIdentifer, for: indexPath) as! HMComposePictrueViewCell
        if indexPath.item == images.count {
            //  最后一cell
            cell.image = nil
        } else {
            cell.image = images[indexPath.item]
            //  注意循环引用
            cell.deleteClosure = { [weak self] in
                self?.images.remove(at: indexPath.item)
                if self?.images.count == 0 {
                    self?.isHidden = true
                }
                self?.reloadData()
            }
        }
        
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if indexPath.item == images.count {
            //  最后一个cell
            addImageCallBack?()
        }
    }
    
}

class HMComposePictrueViewCell: UICollectionViewCell {
   
    // MARK:    --懒加载
    private lazy var imageView: UIImageView = UIImageView(image: UIImage(named: ""))
    private lazy var deleteImageButton: UIButton = {
        let button = UIButton()
        button.addTarget(self, action: #selector(deleteButtonAction), for: .touchUpInside)
        button.setImage(UIImage(named: "compose_photo_close"), for: .normal)
        return button
    }()
    //  执行删除图片的操作
    var deleteClosure: (()->())?
    var image: UIImage? {
        didSet {
            if image == nil {
                imageView.image = UIImage(named: "compose_pic_add")
                deleteImageButton.isHidden = true
            } else {
                imageView.image = image
                deleteImageButton.isHidden = false
            }
            
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    // MARK: -- 点击删除
    @objc private func deleteButtonAction() {
        deleteClosure?()
    }
    
    
    private func setupUI() {
        contentView.addSubview(imageView)
        contentView.addSubview(deleteImageButton)
        imageView.snp_makeConstraints { (make) in
            make.edges.equalTo(contentView)
        }
        deleteImageButton.snp_makeConstraints { (make) in
            make.trailing.equalTo(imageView)
            make.top.equalTo(imageView)
        }
    }
}












